<?php

namespace App\Http\Controllers\System;

use App\Http\Controllers\Controller;
use App\Http\Requests\System\Admin\StoreRequest;
use App\Http\Requests\System\Admin\UpdateRequest;
use App\Http\Resources\System\Admin\IndexResource;
use App\Http\Resources\System\Admin\InfoResource;
use App\Models\System\Admin;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Spatie\QueryBuilder\QueryBuilder;

class AdminController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $list = QueryBuilder::for(Admin::class, $request)
            ->allowedFilters(['id', 'username', 'nickname', 'status', 'mobile', 'email'])
            ->allowedSorts('id')
            ->with('roles')
            ->paginate();

        return $this->success(IndexResource::collection($list));
    }

    public function show(Admin $admin): JsonResponse
    {
        return $this->success(new InfoResource($admin));
    }

    public function store(StoreRequest $request): JsonResponse
    {
        $data = $request->validated();
        /** @var Admin $admin */
        $admin = $request->user();
        $row = new Admin($data);
        $row->save();
        if (! empty($data['roles_ids'])) {
            $row->roles()->attach($admin->getRolesIds()->intersect($data['roles_ids']));
        }

        return $this->success([
            'id' => $row->id,
        ], 'store success');
    }

    public function update(Admin $admin, UpdateRequest $request): JsonResponse
    {
        $data = $request->validated();
        /** @var Admin $user */
        $user = $request->user();
        $admin->fill($data);
        $admin->save();
        if (! empty($data['roles_ids'])) {
            $admin->roles()->sync($user->getRolesIds()->intersect($data['roles_ids']));
        } else {
            $admin->roles()->detach();
        }

        return $this->success(new InfoResource($admin), 'update success');
    }

    public function destroy(Admin $admin): JsonResponse
    {
        $admin->delete();

        return $this->success([], 'delete success');
    }
}
